<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>

    <button-area :style="{ paddingLeft: '80px' }"></button-area>
    <FilterTable
      ref="table"
      columnsRef="testindex"
      :isExportExcel2="true"
      exportFileName="PDI检查区域.xlsx"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectData"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="detailHandle(null,'add')">新增</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="openimportPjDialog()">导入区域</el-button>
        <el-button size="small" type="primary" @click="changeqybz('10031001')" :disabled="isOpen">启用</el-button>
        <el-button size="small" type="primary" @click="changeqybz('10031002')" :disabled="isOpen">停用</el-button>
      </template>
    </FilterTable>

    <!-- 编辑窗口 -->
    <BaseDialog
      :visible.sync="visibleDrawer"
      :title="title"
      width="30%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <info-model v-model="initData" :type="handleType" :rowData="formData" @close="infoClose" />
    </BaseDialog>

    <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportFlag" width="80vw" title="区域导入" destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <ExcelImport
        ref="import"
        template-file-name="区域导入模板.xlsx"
        :importRules="importRules"
        :onComplete="importComplete"
        @close="visibleImportFlag = false"
      />
    </BaseDialog>
  </div>
</template>

<script>
import infoModel from './infoModel';
import { getAreaData, batchUpdate, saveExcel } from '@/api/serviceass/pdimanage/area';
import { dictionary } from '@/utils/dictMixin';
import ExcelImport from '@/components/ExcelImport';
export default {
  name: 'servicessbpdimanageareaindex',
  mixins: [dictionary],
  components: {
    infoModel,
    ExcelImport
  },
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      fetchParams: { xhrAbort: true },
      columns: this.createTableColumns(),
      fetchApi: getAreaData,
      visibleDrawer: false,
      handleType: '',
      formData: {},
      title: 'PDI检查区域维护',
      initData: {},
      isOpen: true,
      visibleImportFlag: false,
      importRules: [
        {prop: 'fwqymc', title: '区域名称',
          rule: [
          { required: true, message: '区域不能为空' },
          {
            validator: (callback, rule, val, row, datas) => {
              this.getAreasList(val).then(res => {
                if (res.resultCode === 200) {
                  const datas = res.data.records.filter(i => i.fwqymc == val)
                  if (datas.length > 0) {
                    console.info('已存在的区域')
                    callback(new Error('已存在的区域'))
                  } else {
                    console.info(datas)
                    callback()
                  }
                } else {
                  callback(new Error(res.errMsg || '验证失败'))
                }
              })
            }
          }
        ]},
        {prop: 'fwyxjb', title: '优先级',
          rule: [
          { required: true, message: '优先级不能为空' },
          {pattern: /(^[1-9]\d*$)/, message: '请填写正确的优先级'}
        ]},
        // {prop: 'bjxmbh', title: '启用标记'},
      ]
    }
  },
  mounted() {
    // 分页
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.initColunm()
  },
  methods: {
    async initColunm() {
      this.columns.find(x => x.dataIndex == 'xtqybz').dictItems = this.createDictList('1003')
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '区域',
          fieldName: 'fwqymc'
        },
        {
          type: 'SELECT',
          label: '启用标记:',
          fieldName: 'xtqybz',
          placeholder: '请选择...',
          itemList: this.createDictList('1003')
        },
      ]
    },
    createTableColumns(){
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button  size="mini" type="text" onClick={() => this.detailHandle(props.row, 'edit')}>
                  编辑
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '状态',
          dataIndex: 'xtqybz',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          // render: props => {    //编码转汉字
          //   return <span>{this.createDictText(props.row.xtqybz, '1003')}</span>;
          // }
        },
        {
          title: '优先级',
          dataIndex: 'fwyxjb',
          sorter: true,
        },
        {
          title: '区域',
          dataIndex: 'fwqymc',
          sorter: true
        },
        {
          title: '创建人',
          dataIndex: 'createdByStr',
          sorter: true,
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true,
          dateFormat: 'yyyy-MM-dd hh:mm:ss',
        },
        {
          title: '修改人',
          dataIndex: 'updatedByStr',
          sorter: true,
        },
        {
          title: '修改时间',
          dataIndex: 'updatedAt',
          sorter: true,
          dateFormat: 'yyyy-MM-dd hh:mm:ss',
        },
      ];
    },
    changeHandle(val) {
      this.isOpen=true;
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    detailHandle(row, type) {
      this.initData =  {
        type: type,
        data: row,
        id:1001
      }; //行id
      this.formData = row;
      this.handleType = type;
      this.visibleDrawer = true;
    },
    selectData(val) {
      if(val.length>0){
        this.isOpen=false;
        this.tableData = val;
      } else {
        this.isOpen=true;
        this.tableData = [];
      }
    },
    infoClose(rData) {
      this.visibleDrawer = false;
      if (rData.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    async changeqybz(val) {
      let str = '';
      this.tableData.map(x => {
        str += x.id + ',';
      });
      str = str.substring(0,str.length-1)
      const res = await batchUpdate({ ids: str,xtqybz: val });
      this.fetchParams = { ...this.fetchParams };
    },
    openimportPjDialog() {
      this.visibleImportFlag = true
    },
    setParts(callback) {
      getAreaData(this.fetchParams).then(res => {
        callback(res.data.records)
      })
    },
    async importComplete(datas,callback){
      if (datas !== null && datas !== undefined && datas !== [] && datas.length > 0) {
        const res = await saveExcel(datas);
        callback();
        if (res.resultCode === 200) {
          this.visibleImportFlag = false
        }
        this.fetchParams = { ...this.fetchParams };
      } else {
        this.$notify.error({ title: '提示信息', message: '没有数据可以导入' || '操作失败!' });
      }
    },
    getAreasList(val) {
      this.areasList = []
      // this.areasList = getAreaData({ "xtqybz": '10031001' })
      this.areasList = getAreaData({ "fwqymc": val })
      console.info(this.areasList)
      return this.areasList;
    }
  }
}
</script>
